<?php

	const MARGIN_PROXY = 0;
	const MARGIN_INVITER = 1;

	/**
	 * Created by PhpStorm.
	 * User: Administrator
	 * Date: 2016/1/21 0021
	 * Time: 10:02
	 */
	class Distribute {
		private $level = 1;
		private $member_id;
		private $minfo;

		static $config = null;

		static $dis_key = 0xff6600;

		/**
		 * @return int
		 */
		public function getLevel() {
			return $this->level;
		}

		/**
		 * @param int $level
		 */
		public function setLevel($level) {
			$this->level = $level;
		}

		/**
		 * @return mixed
		 */
		public function getMemberId() {
			return $this->member_id;
		}

		/**
		 * @param mixed $member_id
		 */
		public function setMemberId($member_id) {
			$this->member_id = $member_id;
		}

		/**
		 * @return array|null
		 */
		public function getMinfo() {
			return $this->minfo;
		}

		/**
		 * @param array|null $minfo
		 */
		public function setMinfo($minfo) {
			$this->minfo = $minfo;
		}


		function isBuyer() {
			return $this->minfo['is_buyer'] == 1;
		}

		function __construct($member_id) {
			$this->member_id = $member_id;

//        if(!self::checkMember($member_id)){
//            die("this user is not distributer");
//        }

			$this->minfo = ml('proxy')->find($member_id);
			$this->init();
		}

		public function isSpecial() {
			return $this->minfo['is_special'];
		}

		private function init() {
			//得到当前分销商的层级
			$tmp = $this->minfo;

			while ($tmp["parent_id"] > 0 && $tmp = ml("proxy")->find($tmp["parent_id"])) {
				$this->level++;
			}

			//载入配置
			if (!self::$config) {
				try {
					self::$config = include(DISINCLUDE . "config.php");
				} catch (Exception $e) {
					self::$config = include(DISINCLUDE . "config_default.php");
				}
			}

			//创建店铺
			if (!ml("proxy_store")->where(array("member_id" => $this->minfo["member_id"]))->count()) {
				ml("proxy_store")->insert(array(
					"member_id" => $this->minfo["member_id"],
					"name"      => (empty($this->minfo["member_truename"]) ? $this->minfo["member_name"] : $this->minfo["member_truename"]) . "的小店",

				));
			}
		}

		public function _getChildren() {
			return self::getChildren($this->member_id);
		}

		public function _getChildrenId() {
			return self::getChildrenId($this->member_id);
		}

		/**
		 * 得到下属层级会员的个数，参数deep只能比当前的等级大
		 *
		 * @param $deep
		 */
		public function getLevelChildrenCount($deep) {
			$level = $this->level;
			if ($deep < $level) {
				return 0;
			}
			$get_count = function ($member_id) use (&$level, $deep, &$get_count) {
				$children = Distribute::getChildrenId($member_id);
				$count = 0;
				if (++$level < $deep) {
					foreach ($children as $child) {
						$count += $get_count($child);
					}
				} else {
					$count = count($children);
				}
				return $count;
			};
			$total = $get_count($this->member_id);
			return $total;
		}

		/**
		 * 得到直到这个层级的所有会员的个数，同上，参数deep只能比当前的等级大
		 *
		 * @param $deep
		 */
		public function getTotalChildrenCount($deep) {
			if ($deep < $this->level) {
				return 0;
			}
			$count = 0;
			$level = $this->level;
			while ($level++ < $deep) {
				$count += $this->getLevelChildrenCount($level);
			}
			return $count;
		}

		/**
		 * 返回某一个等级的所有会员资料
		 */
		public function getLevelMember($deep) {
			$level = $this->level;
			$condition = array($this->member_id);
			$result = array();
			//直属会员
			if ($this->getLevel() + 1 == $deep) {
				$members = ml('proxy')->order('time desc')->select('parent_id = ' . $this->member_id);
			} else {
				$members = ml('proxy')->order('time desc')->select('parent_id = ' . $this->member_id);
				if ($members) {
					$condition = array_merge($condition,array_map(function ($item) {
						return $item['member_id'];
					}, $members));
					$members = ml('proxy')->order('time desc')->select("parent_id in (" . implode(',', $condition) . ')');
				}

			}
			$ret = [];
			if ($members) {
				foreach ($members as $member) {
					$ret[$member['member_id']] = $member;
				}
			}

			return $ret;


//        while ($level < $deep) {
//            $members = ml('proxy')->order('time desc')->select("parent_id in (" . implode(',',$condition) . ')');
//            if (!$members) {
//                $members = array();
//            }
//            $condition = array();
//            foreach ($members as $member) {
//                $condition[] = $member['member_id'];
//                if ($deep - 1 == $level) {
//                    $result[$member['member_id']] = $member;
//                }
//            }
//            $level++;
//        }
//        return $result;
		}

		/**
		 * 返回一颗树，包含所有会员的ID，如需要详细信息再自行查找
		 */
		public static function getTree() {

			$build_nodes = function ($member_id) use (&$build_nodes) {
				$children = Distribute::getChildrenId($member_id);
				$node = array();
				$node["member_id"] = $member_id;
				$node["children"] = array();
				foreach ($children as $child) {
					$node["children"][] = $build_nodes($child);
				}
				return $node;
			};
			$root = $build_nodes(0);
			return $root;
		}

		/**
		 * 得到当前一个ID的所有子集树
		 */
		public static function getChildren($member_id) {
			$children = ml("proxy")->where("parent_id = {$member_id}")->select() or $children = array();
			return $children;
		}

		/**
		 * 同上，返回一个数组ID
		 *
		 * @param $member_id
		 */
		public static function getChildrenId($member_id) {
			$_children = self::getChildren($member_id);
			$children = array_map(function ($item) {
				return $item["member_id"];
			}, $_children);
			return $children;
		}

		/**
		 * 该用户是否是分销客户
		 *
		 * @param $member_id
		 * @return boolean
		 */
		public static function checkMember($member_id) {
			$is_wechat = (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false);
			return ml("proxy")->count($member_id) && $is_wechat;
		}

		/**
		 * 得到链接中已经存在的分享者的ID
		 *
		 */
		public static function getTopMember() {
			if (!isset($_GET['u'])) {
				return null;
			}
			try {
				$levels = (base64_decode(trim($_GET['u'])));
				return $levels;
			} catch (Exception $e) {
			}
			return null;

		}

		public static function autoConfirm($member_id) {
			$auto_days = 7;
			$sql = "SELECT
                        o.*
                    FROM
                        ra_weproxy_order_margin we
                    LEFT JOIN ra_order o ON o.order_id = we.order_id
                    left join ra_order_log l on o.order_id = l.order_id
                    WHERE
                        o.order_state = 30 
                        and o.lock_state = 0 
                        and o.refund_state = 0 
                        and o.delete_state = 0 
                        and l.log_order_state = 30
                        and ".(TIMESTAMP - $auto_days * 86400) . " > l.log_time
            ";
			$res = null;
//            echo $sql;
//            exit;
			$res = Model()->query($sql);
			if ($res) {
				$logic_order = Logic('order');
				foreach ($res as $order) {
					$result = $logic_order->changeOrderStateReceive($order,'system','系统','超期未收货系统自动完成订单');
				}
			}

		}


		/**
		 * 添加一个分销商会员
		 */
		function addProxy($child_id) {
			$info = Model()->table('proxy')->where(['member_id' => $child_id])->find();
			//如果已经存在了，那么不允许再添加
			if ($info) {
				return false;
			}
			return Model()->table('proxy')->insert(array(
				'member_id' => $child_id,
				'time'      => time(),
				'parent_id' => $this->member_id,
				'is_guest'  => 1,
				'is_buyer'  => 0
			));
		}

		/**
		 * 添加一个买家
		 */
		function addBuyer($buyer_id) {
			$info = Model()->table('proxy')->where(['member_id' => $buyer_id])->find();
			//如果已经存在了，那么不允许再添加
			if ($info) {
				dis_log("该用户已经是分销会员了，不能加为别人的");
				return false;
			}
			/**
			 * 以防万一，不增加一级代理商
			 */
			if (empty($this->member_id)) {
				dis_log("该用户不存在！");
				return false;
			}

			dis_log("添加完毕，请检查是否添加成功");
			return Model()->table('proxy')->insert(array(
				'member_id' => $buyer_id,
				'time'      => time(),
				'parent_id' => $this->member_id,
				'is_guest'  => 1,
				'is_buyer'  => 1
			));
		}

		/**
		 * 得到一个会员的预订父级会员
		 *
		 * @param $member_id
		 */
		static function getPreParent($member_id) {
			echo $member_id;
			$minfo = Model('member')->find($member_id);

			dis_log("会员ID是：" . $member_id);
			dis_log("是否查到会员信息：" . (!empty($minfo) ? "yes" : "no"));
			if (!isset($minfo['wechat_openid'])) {
				dis_log("会员不存在openid");
				return null;
			}
			$minfo = Model('proxy_pre')->where(['openid' => $minfo['wechat_openid']])->find();
			if (!$minfo) {
				dis_log("没有在pre表中查到上级会员");
				return null;
			}
			if (empty($minfo['parent_id'])) {
				dis_log("没有找到parent_id");
				return null;
			}
			dis_log("已通过审核");
			return new Distribute($minfo['parent_id']);
		}

		/**
		 * 给一个会员添加分销会员
		 *
		 * @param $proxy_id           上级会员ID
		 * @param $child_id           下线ID
		 * @param bool|true $is_proxy 成为下级分销商还是直属买家，由于有层级限制，当上级会员所属层级大于3的时候，该属性无效
		 */
		public static function addProxyChild($child_id, $is_proxy = false) {
			if (!isset($_SESSION['proxy_top']) && !$is_proxy) {
				return false;
			}

			if ($is_proxy) {
				$proxy_id = base64_decode(trim($is_proxy)) >> 16;
				if ($proxy_id > 0) {
					$proxy_info = ml('proxy')->where(array('member_id' => $proxy_id))->find();
					if ($proxy_info) {
						ml('proxy')->insert(array(
							'member_id' => $child_id,
							'time'      => time(),
							'parent_id' => $proxy_id,
							'is_guest'  => 1,
							'is_buyer'  => 1,
						));
						return true;
					}
				}
			} else {
				$proxy_id = $_SESSION['proxy_top'];
			}

			if (!self::checkMember($proxy_id)) {
				return false;
			}

			$top_distribute = new Distribute($proxy_id);
			if ($top_distribute->getLevel() >= self::$config['levels']) {
				$is_proxy = false;
			}

			$new_id = ml('proxy')->insert(array(
				"member_id"     => $child_id,
				"parent_id"     => $proxy_id,
				"infomation"    => '',
				'price_formula' => '',
				'time'          => time(),
				"is_buyer"      => 1
			), true);

			//将apply中所有的申请撤销
//        ml('proxy_apply')->where('member_id = ' . $child_id)->update(array('status'=>'state_cancel'));

			if ($new_id) {
				return true;
			}

			return false;
		}


		/**
		 * 初始化proxy店铺，为了防止没有创建店铺
		 */
		public function init_proxy_store() {

		}

		public function updateStoreSetting($data) {
			return ml('proxy_store')->where(array("member_id" => $this->minfo["member_id"]))->update($data);
		}

		public function getStoreSetting() {
			$ret = ml("proxy_store")->where(array("member_id" => $this->minfo["member_id"]))->find();
			return $ret ? $ret : array();
		}


		/**
		 * 给微店添加一个商品
		 *
		 * @param $goods_id
		 * @return bool|null
		 */
		public function addGoods($goods_id) {
			$ginfo = ml("goods")->find($goods_id);
			if (!ml("proxy_store_goods")->where(array(
				"member_id"      => $this->minfo["member_id"],
				"goods_commonid" => $ginfo["goods_commonid"]
			))->count()
			) {
				if (ml("proxy_store_goods")->insert(array(
					"member_id"      => $this->minfo["member_id"],
					"goods_commonid" => $ginfo["goods_commonid"],

				))
				) {
					return true;
				}
				return null;
			} else {
				return false;
			}
		}

		public function makeProxyLink() {
			$top_member = self::getTopMember();
			if ($top_member && $top_member == $this->minfo["member_id"]) {
				return;
			}
//        $_GET['u'] = base64_encode($this->minfo["member_id"]);
			unset($_GET['u']);
			unset($_GET['act']);
			unset($_GET['op']);
			$href = "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"] . '?' . http_build_query($_GET);
			header("location:$href");
			exit;
		}

		/**
		 * 返回当前用户收藏的所有商品
		 */
		public function getAllGoods() {
			$result = array();
			$gmids = ml('proxy_store_goods')->select("member_id = {$this->member_id}");
			foreach ($gmids as $item) {
				$result[] = ml('goods_common')->find($item['goods_commonid']);
			}
			return $result;
		}

		public function checkGoods($goods_id) {
			if (is_array($goods_id)) {
				$ginfo = $goods_id;
			} else {
				$ginfo = ml('goods')->find($goods_id);
			}
			return ml('proxy_store_goods')->count('member_id=' . $this->member_id . ' and goods_commonid = ' . $ginfo['goods_commonid']);
		}

		public function deleteGoods($arr) {
			return ml('proxy_store_goods')->where($arr)->delete();
		}

		public function calMarginByGoods($goods_id) {
			$ginfo = $ginfo = ml('goods')->find($goods_id);
			$gminfo = ml('goods_common')->find($ginfo['goods_commonid']);
			$rate = unserialize($gminfo['distribute_rate']);
			//如果有分销价格，那么使用分销的价格
			if($gminfo['distribute_price'] > 0){
				$total_money = $gminfo['distribute_price'];
			}
			else{
				$total_money = $ginfo['goods_price'];
			}
			//如果是特殊的分销商
			if($this->minfo['is_special']){
				$margin = $total_money * $gminfo['distribute_special'] / 100;
			}
			else{
				$margin = $total_money * $rate[$this->level - 1] / 100;
			}
			if ($margin <= 0) {
				$margin = 0;
			}

			return sprintf("%.2f", $margin);
		}

		/**
		 * 返回当前用户的某个订单商品计算价格
		 */
		public function calMarginByOrderGoods($rec_id) {
			/**
			 * 如果只是买家，那么提成为0
			 */
//			if ($this->minfo['is_buyer'] == 1) {
//
//			}

			$oginfo = ml('order_goods')->find($rec_id);
			/**
			 * 如果这个商品不是我买的，那么返回0
			 */
//        $oinfo = ml('order')->find($oginfo['order_id']);
//        if ($oinfo['buyer_id'] != $this->minfo['member_id']) {
//            return 0;
//        }
			/**
			 * 如果这个商品不再分享的店铺里，那么返回0
			 */
			$ginfo = ml('goods')->find($oginfo['goods_id']);
			$gminfo = ml('goods_common')->find('goods_commonid = ' . $ginfo['goods_commonid']);

			//如果这个商品没有参加分销，那么就不计算
			if($gminfo['agree_distribute'] != 1){
				return 0;
			}
//        if (!ml('proxy_store_goods')->find("goods_commonid = {$ginfo['goods_commonid']} and member_id = {$this->member_id}")) {
//            return 0;
//        }


			$total_money = $oginfo['goods_price'] * $oginfo['goods_num'];
			$rate = unserialize($gminfo['distribute_rate']);
			//上级的利润
			if ($this->isSpecial()) {
				$margin = $total_money * $gminfo['distribute_special'] / 100;
			}
			else if(!$this->isBuyer()){
				$margin = $total_money * $rate[$this->level - 1] / 100;
			}
			else{
				$margin = 0;
			}

			//当前会员推荐人的利润
			$inviter = $this->getInviter();

			if ($inviter) {
				$in_rate = unserialize($gminfo['dis_inv_rate']);
				if ($inviter->isSpecial()) {
					$in_margin = $total_money * $gminfo['dis_spec_rate'] / 100;
				}
				else{
					$in_margin = $total_money * $in_rate[$this->level - 1] / 100;
				}
//				echo $total_money;
//				print_r($in_rate);
//				print_r($this->level);
//				print_r($inviter->isSpecial());
//				exit;
			}
			if (!$in_margin || $in_margin <= 0) {
				$in_margin = 0;
			}

			if ($margin <= 0) {
				$margin = 0;
			}
//			if ($this->isBuyer()) {
//				$margin = 0;
//			}
			return [
				sprintf("%.2f", $margin),
				//推荐人需要指明是谁
				[sprintf("%.2f", $in_margin),$inviter->member_id]
			];
		}

		public function calMarginByOrder($order_id) {
			$oinfo = ml('order')->find($order_id);
			if (!$oinfo) {
				return [0,0];
			}
			$order_goods = ml('order_goods')->select('order_id=' . $order_id);
			$total = 0;
			$in_total = 0;
			$inviter_id = -1;
			foreach ($order_goods as $goods) {
				list($margin,$in_margin) = $this->calMarginByOrderGoods($goods['rec_id']);
				$total += $margin;
				$in_total += $in_margin[0];
				$inviter_id = $in_margin[1];
			}
//			echo ml('member')->find($this->member_id)['member_name'] . "应得利润：" . $total . PHP_EOL;
//			echo ml('member')->find($inviter_id)['member_name'] . "推荐利润：" . $in_total . PHP_EOL;

			return [$total,$in_total,$inviter_id];
		}

		/**
		 * 得到某一个会员的父亲
		 */
		public function getParent() {
			$proxy_info = ml('proxy')->find($this->minfo['member_id']);
			if ($proxy_info['parent_id'] == 0 || !$proxy_info) {
				return null;
			}
			$proxy = ml("proxy")->find("member_id=" . $proxy_info['parent_id']);
			return new self($proxy['member_id']);
		}

		/**
		 * 得到当前会员的推荐人
		 */
		public function getInviter(){
			$minfo = ml('member')->find([
				'member_id' => $this->minfo['member_id'],
			]);
			if (!$minfo) {
				return null;
			}
			$inviter = ml('proxy_pre')->find([
				'openid' => $minfo['wechat_openid']
			]);
			if (!$inviter) {
				return null;
			}
			$inviter = ml('proxy')->find([
				'member_id' => $inviter['parent_id'],
			]);
			if (!$inviter) {
				return null;
			}
			return new self($inviter['member_id']);
		}

		/**
		 * 计算某一个订单的提成，一直向上计算到最上级
		 *
		 * @param $order_id
		 */
		public static function calMargin($order_id) {
			$oinfo = ml('order')->find($order_id);
			$buyer_distribute = new self($oinfo['buyer_id']);
			$now = $buyer_distribute;
			$ret = array();
			do {
				$ret[$now->member_id] = $now->calMarginByOrder($order_id);
			} while ($now = $now->getParent());
			return $ret;
		}

		/**
		 * 将某一个订单的利润加上
		 *
		 * @param $order_id
		 */
		public static function giveMargin($order_id) {
			$arr = Distribute::calMargin($order_id);
			$oinfo = ml('order')->find($order_id);
			foreach ($arr as $member_id => $data) {
				$margin = $data[0];
				if ($margin <= 0) {
				}
				else{
					$distribute = new Distribute($member_id);
					ml('weproxy_order_margin')->insert(array(
						'order_id'    => $order_id,
						'member_id'   => $member_id,
						'margin'      => $margin,
						'level'       => $distribute->getLevel(),
						'time'        => TIMESTAMP,
						'from_member' => $oinfo['buyer_id'],
						'type' => MARGIN_PROXY
					));
				}

				$inviter = $data[2];
				$in_margin = $data[1];
				if ($in_margin <= 0) {

				}
				else{
					$distribute = new Distribute($inviter);
					ml('weproxy_order_margin')->insert(array(
						'order_id'    => $order_id,
						'member_id'   => $distribute->member_id,
						'margin'      => $in_margin,
						'level'       => $distribute->getLevel(),
						'time'        => TIMESTAMP,
						'from_member' => $oinfo['buyer_id'],
						'type' => MARGIN_INVITER
					));
				}
				//$minfo = ml('member')->find($member_id);
//            ml('member')->where('member_id=' . $member_id)->update(array('available_predeposit' => $minfo['available_predeposit'] + $margin));
//            ml('pd_log')->insert(array(
//                'lg_member_id' => $minfo['member_id'],
//                'lg_member_name' => $minfo['member_name'],
//                'lg_admin_name' => '',
//                'lg_type' => 'recharge',
//                'lg_av_amount' => $margin,
//                'lg_freeze_amount' => 0,
//                'lg_add_time' => time(),
//                'lg_desc' => '订单 ' . $oinfo['order_sn'] . ' 的佣金'
//            ));


			}
		}

		public function confirm($order_id) {
			$margin_infos = ml('weproxy_order_margin')->select(['order_id' => $order_id]);
			if(empty($margin_infos)){return;}
			foreach ($margin_infos as $margin_info) {
				$minfo = null;
				$oinfo = null;
				$minfo = ml('member')->find($margin_info['member_id']);
				$oinfo = ml('order')->find($order_id);
				if (!$margin_info || !$minfo || !$oinfo) {
					return;
				}
				ml('member')->where('member_id=' . $minfo['member_id'])->update(array('available_predeposit' => $minfo['available_predeposit'] + $margin_info['margin']));
				ml('pd_log')->insert(array(
					'lg_member_id'     => $minfo['member_id'],
					'lg_member_name'   => $minfo['member_name'],
					'lg_admin_name'    => '',
					'lg_type'          => 'recharge',
					'lg_av_amount'     => $margin_info['margin'],
					'lg_freeze_amount' => 0,
					'lg_add_time'      => time(),
					'lg_desc'          => '订单 ' . $oinfo['order_sn'] . ' 的佣金' . ($margin_info['type'] == MARGIN_INVITER ? "（推荐人）" : "")
				));
			}

		}

		/**
		 * 如果一个会员是买家，那么直接取消
		 * 如果是分销会员，下级会员全部给到上级
		 */
		public function cancelPermission() {
			if ($this->isBuyer()) {
				return $this->remove($this->member_id);
			}

			ml('proxy')->where(['parent_id' => $this->member_id])->update([
				'parent_id' => $this->minfo['parent_id']
			]);
			return $this->remove($this->member_id);
		}

		/**
		 * 删除一个会员
		 */
		public function remove($v) {
			$member = ml('member')->find($v);
			//微分销的删除处理
			Model()->table('proxy')->where(['member_id' => $v])->delete();
			Model()->table("proxy_apply")->where(['member_id' => $v])->delete();
			//删除预申请
			if (!empty($member['wechat_openid'])) {
				Model('proxy_pre')->where(['openid' => $member['wechat_openid']])->delete();
			}
			//删除店铺
			Model('proxy_store')->where(['member_id' => $v])->delete();
			//删除店铺商品
			Model('proxy_store_goods')->where(['member_id' => $v])->delete();
		}

		public static function isProxy($member_id) {
			return ml('proxy')->find($member_id);
		}


	}


	function dis_log($content) {
		file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/dis_log.txt', $content . PHP_EOL, FILE_APPEND);
	}

	//test
	//new Distribute(10);
	//
	//Distribute::getTree();